package org.pointex.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.pointex.common.controller.BaseController;
import org.pointex.common.model.PageEntity;
import org.pointex.common.model.PagingResult;
import org.pointex.common.util.constant.Constant;
import org.pointex.dao.impl.ConvertIndentDaoImpl;
import org.pointex.dao.impl.CreditsRecordDaoImpl;
import org.pointex.dao.impl.DeliveryInfoDaoImpl;
import org.pointex.dao.impl.UsersDaoImpl;
import org.pointex.dao.impl.ViewConvertUtilDaoImpl;
import org.pointex.domain.DeliveryInfo;
import org.pointex.domain.Users;
import org.pointex.service.MaxNoService;
import org.pointex.util.DateUtil;
import org.pointex.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @ClassName: MemberController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author Kenny_Z' szqiuk@gmail.com
 * @date 2016年10月23日 下午9:18:30
 *
 */
@Controller
@RequestMapping("/View/member/")
public class MemberController extends BaseController {

	@Autowired
	private CreditsRecordDaoImpl creditsRecordDaoImpl;

	@Autowired
	private ConvertIndentDaoImpl convertIndentDaoImpl;

	@Autowired
	private ViewConvertUtilDaoImpl viewConvertUtilDaoImpl;

	@Autowired
	private DeliveryInfoDaoImpl deliveryInfoDaoImpl;

	@Autowired
	private UsersDaoImpl usersDaoImpl;

	@Autowired
	private MaxNoService maxNoService;

	@RequestMapping("address")
	public ModelAndView address() {
		return new ModelAndView();
	}

	/**
	 * 获取登录用户的所有收货信息
	 * 
	 * @param offset
	 *            当前页
	 */
	@RequestMapping(value = "getUserAllAddress", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void getUserAllAddress(@Valid int offset,
			HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			Users users = getUsersItem(request);
			Map param = new HashMap();
			param.put("userId", users.getUserId());
			param.put("delFlag", false);

			PageEntity pageEntity = new PageEntity(offset, 3, param, "status",
					"desc");
			PagingResult<DeliveryInfo> addresslist = deliveryInfoDaoImpl
					.selectPagination(pageEntity);
			jsonObject.put("item", addresslist);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				feedback(response, jsonObject.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "updateAddress", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void updateAddress(@Valid int id, @Valid String action,
			HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			Users users = getUsersItem(request);
			DeliveryInfo deliveryInfo;
			Map param = new HashMap();
			param.put("userId", users.getUserId());

			if (action.equals("update")) {// 更改默认地址时 ，其他地址重置为非默认地址
				try {
					param.put("status", 0);
					deliveryInfoDaoImpl.updateParam(param);
					System.out.println("----------重置成功");
					param.put("status", 1);
					param.put("id", id);
					deliveryInfoDaoImpl.updateParam(param);
					System.out.println("设置默认收货地址成功");
					jsonObject.put("result", 1);// 设置默认值成功
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					jsonObject.put("result", 0);// 设置默认值失败
				}
			} else if (action.equals("delete")) {// 删除地址
				try {
					param.put("id", id);
					param.put("delFlag", 1);
					deliveryInfoDaoImpl.updateParam(param);
					jsonObject.put("result", 2);// 删除地址成功
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					jsonObject.put("result", 3);// 删除地址失败
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				feedback(response, jsonObject.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "address1", method = RequestMethod.GET)
	public ModelAndView address1() {
		ModelAndView mav = new ModelAndView();
		try {
			Map param = new HashMap();
			Users users = getUsersItem(request);
			param.put("id", request.getParameter("id"));
			param.put("userId", users.getUserId());
			String id = request.getParameter("id");
			DeliveryInfo deliveryInfo = new DeliveryInfo();
			if (!StringUtil.isNullOrEmpty(id)) {
				List<DeliveryInfo> list = deliveryInfoDaoImpl
						.selectParam(param);
				if (list.size() > 0)
					deliveryInfo = list.get(0);
			}
			mav.addObject("item", deliveryInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mav;
	}

	@RequestMapping(value = "addAddress", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void addAddress(@Valid DeliveryInfo deliveryInfo) {
		JSONObject jsonObject = new JSONObject();
		int id = deliveryInfo.getId() == null ? 0 : deliveryInfo.getId();
		int result = 0;
		try {
			Users users = getUsersItem(request);
			deliveryInfo.setUpdateDt(DateUtil
					.formatDate_YYYYMMDDHHMMSS(new Date()));
			deliveryInfo.setUserId(users.getUserId());
			if (id == 0) {
				deliveryInfo.setDelivery(maxNoService
						.updateGetNextNo(Constant.MAXNO_DE_NO));
				deliveryInfo.setCreateDt(DateUtil
						.formatDate_YYYYMMDDHHMMSS(new Date()));
				deliveryInfo.setDelFlag(new Byte((byte) 0));
				deliveryInfo.setStatus(new Byte((byte) 0));
				result = deliveryInfoDaoImpl.insertSelective(deliveryInfo);
			} else
				result = deliveryInfoDaoImpl
						.updateByPrimaryKeySelective(deliveryInfo);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				jsonObject.put("result", result);
				feedback(response, jsonObject.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@RequestMapping("exchange")
	public ModelAndView exchange() {
		return new ModelAndView();
	}

	@RequestMapping("integral")
	public ModelAndView integral() {
		ModelAndView mav = new ModelAndView();
		int totalCredits = 0;
		Users users = getUsersItem(request);
		totalCredits = users.getCredits();
		// List<CreditsRecord> records =
		// creditsRecordDaoImpl.selectParam(param);
		// for (CreditsRecord creditsRecord : records) {
		// if (creditsRecord.getCreditsState().equals("添加积分")) {
		// totalCredits += creditsRecord.getCreditsValue();
		// } else if (creditsRecord.getCreditsState().equals("消费积分")) {
		// totalCredits -= creditsRecord.getCreditsValue();
		// }
		// }
		mav.addObject("totalCredits", totalCredits);
		return mav;
	}

	// 我的积分
	@RequestMapping(value = "getUserCreditsRecord", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void getUserCreditsRecord(@Valid int offset,
			HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			Users users = getUsersItem(request);
			int totalCredits = 0;
			Map param = new HashMap();
			param.put("userId", users.getUserId());

			PageEntity pageEntity = new PageEntity(offset, 2, param,
					"a.create_dt", "desc", "selectParamCreditsRecord",
					"countParamCreditsRecord");
			PagingResult<Hashtable<Object, Object>> records = viewConvertUtilDaoImpl
					.selectPagination(pageEntity);
			jsonObject.put("item", records);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				feedback(response, jsonObject.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// 兑换记录
	@RequestMapping(value = "getUserConvertIndent", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void getUserConvertIndent(@Valid int offset,
			HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			Users users = getUsersItem(request);
			int totalCredits = 0;
			Map param = new HashMap();
			param.put("userId", users.getUserId());

			PageEntity pageEntity = new PageEntity(offset, 2, param,
					"a.create_dt", "desc", "selectParamConvertIndent",
					"countParamConvertIndent");
			PagingResult<Hashtable<Object, Object>> records = viewConvertUtilDaoImpl
					.selectPagination(pageEntity);
			jsonObject.put("item", records);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				feedback(response, jsonObject.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
